package com.easymin.weixin.common.api;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.easymin.weixin.common.DataGrid;
import com.easymin.weixin.common.Distance;
import com.easymin.weixin.common.SignHelper;
import com.easymin.weixin.entity.Intent;
import com.easymin.weixin.entity.Partner;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.math.MathContext;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class PartnerApi {

  @Value("${module.partner.url}")
  private String partnerApiGateway;

  @Value("${module.partner.appId}")
  private String partnerAppId;

  @Value("${module.partner.appKey}")
  private String partnerAppKey;

  @Autowired
  private RestTemplate restTemplate;

  /**
   * 分页查询商家.
   */
  public static final String QUERY_PARTNER =
      "api/partner.json?appKey={appKey}&categoryAlias={categoryAlias}"
          + "&page={page}&rows={rows}&appId={appId}&sign={sign}";

  public static final String QUERY_INTENT =
      "api/intent/findIntents.json?appKey={appKey}&categoryAlias={categoryAlias}"
      + "&appId={appId}&sign={sign}";
  
  /**
   * 分页查询商家.
   */
  
  public DataGrid<Map<String, Object>> findByParam(
      String categoryAlias, Double longitude,
      Double latitude, Long intentId, Integer page, Integer rows, String appKey) {
    DataGrid<Map<String, Object>> dataGrid = new DataGrid<Map<String, Object>>();
    Map<String, String> kv = new HashMap<String, String>();
    kv.put("categoryAlias", categoryAlias);
    if (intentId != null && intentId != 0) {
      kv.put("intentId", String.valueOf(intentId));
    }
    kv.put("page", String.valueOf(page));
    kv.put("rows", String.valueOf(rows));
    kv.put("appKey", appKey);
    kv.put("appId", partnerAppId);
    String sign = SignHelper.sign(SignHelper.buildSignMessage(kv), partnerAppKey);
    kv.put("sign", sign);
    String url = buildApi(QUERY_PARTNER);
    if (intentId != null && intentId != 0) {
      url += "&intentId={intentId}";
    }
    String result = restTemplate.getForObject(url, String.class, kv);
    JSONObject jo = JSON.parseObject(result);
    int code = jo.getIntValue("code");
    List<Map<String, Object>> listMap = new ArrayList<Map<String, Object>>();

    if (code == 0) {
      List<Partner> list = new ArrayList<Partner>();
      JSONObject json = jo.getJSONObject("data");
      long total = json.getLong("total");

      dataGrid.setTotal(total);
      JSONArray jsonArray = json.getJSONArray("rows");
      list = JSON.parseArray(jsonArray.toString(), Partner.class);

      for (int i = 0; i < list.size(); i++) {
        Partner partner = list.get(i);
        Double length = Distance.doubleVal(partner.getLat(), partner.getLng(), latitude, longitude);
        if (length > 0 && length <= 1) {
          BigDecimal decimal = new BigDecimal(1000 * length);
          BigDecimal abs = decimal.abs(new MathContext(3));
          String str = abs.intValue() + "米";
          partner.setDistanceStr(str);
          partner.setDistance(new BigDecimal(length).abs(new MathContext(3)).doubleValue());
        } else if (length > 1) {
          BigDecimal decimal = new BigDecimal(length);
          if (length <= 10) {
            BigDecimal abs = decimal.abs(new MathContext(2));
            String str = abs + "公里";
            partner.setDistanceStr(str);
            partner.setDistance(new BigDecimal(length).abs(new MathContext(2)).doubleValue());
          } else if (length > 10 && length < 100) {
            BigDecimal abs = decimal.abs(new MathContext(3));
            String str = abs + "公里";
            partner.setDistanceStr(str);
            partner.setDistance(new BigDecimal(length).abs(new MathContext(3)).doubleValue());
          } else if (length > 100 && length <= 1000) {
            BigDecimal abs = decimal.abs(new MathContext(4));
            String str = abs + "公里";
            partner.setDistanceStr(str);
            partner.setDistance(new BigDecimal(length).abs(new MathContext(4)).doubleValue());
          } else {
            BigDecimal abs = decimal.abs(new MathContext(5));
            String str = abs + "公里";
            partner.setDistanceStr(str);
            partner.setDistance(new BigDecimal(length).abs(new MathContext(5)).doubleValue());
          }

        }
      }
      for (int i = 0; i < list.size(); i++) {
        Partner partner = list.get(i);
        Double dis = partner.getDistance();
        for (int j = 0; j < list.size(); j++) {
          Partner par = list.get(j);
          Double d2 = par.getDistance();
          if (dis < d2) {
            Partner temp = list.get(i);
            list.set(i, par);
            list.set(j, temp);
          }
        }
      }
      for (Partner partner : list) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("categoryId", partner.getCategoryId());
        map.put("categoryName", partner.getCategoryName());
        map.put("categoryAlias", partner.getCategoryAlias());
        map.put("intentId", partner.getIntentId());
        map.put("intentName", partner.getIntentName());
        map.put("name", partner.getName());
        map.put("phone", partner.getPhone());
        map.put("province", partner.getProvince());
        map.put("city", partner.getCity());
        map.put("county", partner.getCounty());
        map.put("address", partner.getAddress());
        map.put("distance", partner.getDistance());
        map.put("distanceStr", partner.getDistanceStr());
        map.put("lat", partner.getLat());
        map.put("lng", partner.getLng());
        map.put("intro", partner.getIntro());
        map.put("imgs", partner.getList());
        listMap.add(map);
      }
    }
    dataGrid.setRows(listMap);

    return dataGrid;
  }

  /**
   * 查询子分类.
   */
  public List<Intent> findIntents(String categoryAlias, String appKey) {
    Map<String, String> kv = new HashMap<String, String>();
    kv.put("categoryAlias", categoryAlias);
    kv.put("appKey", appKey);
    kv.put("appId", partnerAppId);
    String sign = SignHelper.sign(SignHelper.buildSignMessage(kv), partnerAppKey);
    kv.put("sign", sign);

    String result = restTemplate.getForObject(buildApi(QUERY_INTENT), String.class, kv);
    JSONObject jo = JSON.parseObject(result);
    int code = jo.getIntValue("code");
    List<Intent> list = new ArrayList<Intent>();
    if (code == 0) {
      JSONArray jsonArray = jo.getJSONArray("data");
      list = JSON.parseArray(jsonArray.toString(), Intent.class);
    }
    return list;
  }

  private String buildApi(String api) {

    StringBuilder builder = new StringBuilder();
    builder.append(partnerApiGateway);
    if (!partnerApiGateway.endsWith("/")) {
      builder.append("/");
    }
    builder.append(api);

    return builder.toString();
  }

}
